﻿using System;
using System.Text;
using System.IO;
using System.Collections.Generic;

namespace Gencode.Common.ActionLogger
{
    /// <summary>
    /// Type of message to be logged. Type = Name of logg entry.
    /// </summary>
	public enum MessageType { SQL, ODBC, ERROR, ODBC_ERROR, SQL_ERROR, USER_ERROR, USER_EVENT, SYSTEM_EVENT, DATA_EVENT, DATA_ERROR };

    public static class Logger
    {
        static bool useLogger = false;
        static TextWriter writer = null;

		static string logName;
		/// <summary>
		/// Name of the logfile. default = log.log
		/// </summary>
		public static string LogName
		{
			get
			{
				if (string.IsNullOrEmpty(logName))
					return "log.log";

				return logName;
			}
			set
			{
				logName = value;
				UseLogger = true;
			}
		}

		static bool appendLog = true;
		/// <summary>
		/// will apend to the existing logfile if true. will delete and create new logfile if false
		/// </summary>
		public static bool AppendLogFile
		{
			get
			{
				return appendLog;
			}
			set
			{
				appendLog = value;
			}
		}

		/// <summary>
		/// finishes and closes the logfile
		/// </summary>
		public static void Dispose()
		{
			DisposeLogger();
		}

        public static bool UseLogger
        {
            get
            {
                return useLogger;
            }
            set
            {
                useLogger = value;

                if (useLogger)
                    InitializeLogger();
                else
                    DisposeLogger();
            }
        }

        private static void InitializeLogger()
        {
			//dispose older messages
			if(File.Exists(LogName))
			{
				string[] tmpStr = File.ReadAllLines(LogName);
				List<string> tmpStrList = new List<string>();
				tmpStrList.AddRange(tmpStr);


				if (tmpStrList.Count > 40000)
				{
					int cnt = tmpStrList.Count;
					int index = tmpStrList.Count - 2000;
					using (StreamWriter wr = new StreamWriter(LogName, false))
					{

						while (index < cnt)
						{
							if (index < tmpStrList.Count)
								wr.WriteLine(tmpStrList[index]);
							index++;
						}
						wr.Flush();
						wr.Close();
					}
				}
			}
        }

        private static void DisposeLogger()
        {
            if (writer != null)
            {
				//writer.Flush();
				//writer.Close();
				writer.Dispose();
            }
        }

        /// <summary>
        /// Loggs a message/event to log.txt. UseLogger has to be true if the logger wants to be used
        /// </summary>
        /// <param name="messageType">type of message/title of message</param>
        /// <param name="message">message to logg</param>
        public static void LoggMessage(MessageType messageType, string message)
        {
            if (useLogger)
            {
                try
                {
                    string dir = logName.Substring(0, logName.LastIndexOf('\\'));

                    if (dir != string.Empty && !Directory.Exists(dir))
                    {
                        Directory.CreateDirectory(dir);
                    }
                }
                catch { }

                string logMsg = "[" + messageType.ToString() + "][" + DateTime.Now.ToString() + "]    " + message;
                try
                {
                    using (writer = new StreamWriter(LogName, appendLog))
                    {
                        writer.WriteLine(logMsg);
                        writer.Flush();
                        writer.Close();
                    }
                }
                catch(Exception e) 
                {
                    Gencode.Common.Util.ErrorHandler.LoggError("no logfile", "Logger.LoggMessage()", e.Message);
                }
            }
        }
    }
}
